package com.example.innovate.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

//io流写入文件
public class FileUtil {
    //静态方法：三个参数：文件的二进制，文件路径，文件名
    //通过该方法将在指定目录下添加指定文件
    public static void fileupload(byte[] file,String filePath,String fileName) throws IOException {
        //目标目录
        File targetfile = new File(filePath);
        if(targetfile.exists()) {
            targetfile.mkdirs();
        }

        //二进制流写入
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

//  文件上传
    public static String upload(@RequestParam("file") MultipartFile file) throws Exception{
        String fileName = new String();
        if(!file.isEmpty()) {
            fileName = file.getOriginalFilename();
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            String name =  fileName.substring(0,fileName.lastIndexOf("."));
            fileName = name + suffix;
            ClassPathResource resource = new ClassPathResource("");
            String filePath = resource.getPath()+"/root/file/";//  C:\\file\\ C:\\file\\
            File file1 = new File(filePath + fileName);
            int i = 1;
            String Name = new String();
            while (file1.isFile() && file1.exists()) {
                Name = name + i++;
                file1 = new File(filePath + Name + suffix);
                fileName = Name + suffix;
            }
            try {
                FileUtil.fileupload(file.getBytes(), filePath, fileName);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return fileName;
    }

}
